<?php
#----------------------- ERROR FORM --------------------------------------------
define('__FC_ERR_NONE', 						0);
define('__FC_ERR_EMPTY_NAME', 					101);
define('__FC_ERR_CANT_FOUND_FORM_TEMPLATE',		102);
define('__FC_ERR_EMPTY_FIELDS',					103);
define('__FC_ERR_TWIN_NAMES',					104);
define('__FC_ERR_CANT_INCLUDE_FIELD_CLASS',		105);
define('__FC_ERR_CANT_CREATE_SESSION',			106);

$fc_error_str = array();
$fc_error_str[__FC_ERR_EMPTY_NAME] 					= 'FC :: Empty Form Name';
$fc_error_str[__FC_ERR_CANT_FOUND_FORM_TEMPLATE] 	= 'FC :: Can\'t Found Form Template';
$fc_error_str[__FC_ERR_EMPTY_FIELDS] 				= 'FC :: Empty Fields';
$fc_error_str[__FC_ERR_TWIN_NAMES] 					= 'FC :: Form Contain Twin Fields';
$fc_error_str[__FC_ERR_CANT_INCLUDE_FIELD_CLASS] 	= 'FC :: Can\'t Include Class For Type';
$fc_error_str[__FC_ERR_CANT_CREATE_SESSION] 		= 'FC :: Can\'t Create Session, Headers Is Already Sent';

#----------------------- ERROR FIELDS --------------------------------------------
define('__FDC_ERR_NONE', 				0);
define('__FDC_ERR_EMPTY_NAME', 			201);
define('__FDC_ERR_EMPTY_TYPE',			202);
define('__FDC_ERR_EMPTY_TITLE',			203);
define('__FDC_ERR_UNKNOWN_CHECK_FUNC',	204);
define('__FDC_ERR_UPLOAD_DIR',			205);

$fdc_error_str = array();
$fdc_error_str[__FDC_ERR_EMPTY_NAME] 			= 'FDC :: Empty Field Name';
$fdc_error_str[__FDC_ERR_EMPTY_TYPE] 			= 'FDC :: Empty Field Type';
$fdc_error_str[__FDC_ERR_EMPTY_TITLE] 			= 'FDC :: Empty Field Title';
$fdc_error_str[__FDC_ERR_UNKNOWN_CHECK_FUNC] 	= 'FDC :: Unknown Check Function';
$fdc_error_str[__FDC_ERR_UPLOAD_DIR] 			= 'FDC :: Can\'t Write To Upload Dir';

include_once( dirname(__FILE__).'/basic/constant.php' );
include_once( dirname(__FILE__).'/basic/cobject.php' );
include_once( dirname(__FILE__).'/../vtmpl/vlibTemplate.php' );

class CForm extends CObject
{
#-------------------------------------------------------------------------------------------------------------------------
	var $tmplh 	= null;
	var $fields = array();
	var $name	= '';

	var $__err_info = array();
	var $cf_is_submit = false;

#-------------------------------------------------------------------------------------------------------------------------

	function CForm( $name, $fields, $debug = 0 ){
		global $fc_error_str, $err_info, $type_class;

		$chk_types = array();
		$this->debug = intval($debug) ? 1 : 0;

		#set errors str error
		$this->errors_str = & $fc_error_str;
		$this->__err_info = & $err_info;

		#set form name
		if ( $name )
		    $this->name = $name;
		else
		    $this->__raise_error(__FC_ERR_EMPTY_NAME, __FILE__, __LINE__);

		#create fields objects
		if ( !empty($fields) && is_array($fields) ){
			$fields = array_change_key_case($fields, CASE_LOWER);
			$index = sizeof($fields);
			for($i=0; $i<$index; $i++){
				#looking for twin names
				if ( $fields[$i]['name'] && array_key_exists($fields[$i]['name'], $chk_types) ){
					$this->__raise_error(__FC_ERR_TWIN_NAMES,__FILE__,__LINE__);
				}else{
					$chk_types[$fields[$i]['name']] = 0;
				}
				$class_name = $type_class[strtolower($fields[$i]['type'])];
				$try_include = @include_once( dirname(__FILE__).'/fields/'.$class_name.'.php' );
				if ( $try_include ){
					$this->fields[] = & new $class_name($fields[$i], $this->__err_info, $debug);
				}else{					$this->__raise_error(__FC_ERR_CANT_INCLUDE_FIELD_CLASS,__FILE__,__LINE__, dirname(__FILE__).'/fields/'.$class_name.'.php' );
				}
			}
		}else{			$this->__raise_error(__FC_ERR_EMPTY_FIELDS, __FILE__, __LINE__);
		}
	}

#-------------------------------------------------------------------------------------------------------------------------

	function Desrtoy(){
		$index = sizeof($this->fields);
		for($i=0; $i<$index; $i++){
			$this->fields[$i]->Free();
		}
		parent :: Destroy();
	}

#-------------------------------------------------------------------------------------------------------------------------

	function cf_set_submit( &$values ){
		$this->cf_is_submit = false;
		#add is_submit
		if ( $values['__submit'] )
		    $this->cf_is_submit = true;
	}

#-------------------------------------------------------------------------------------------------------------------------

	function cf_set_values( &$values, &$vars, $js_protect = 1 ){
		$this->cf_set_submit( $values );
		$values_correct = $values;
		#очищаем от префиксов если js не сработал
		if( $this->cf_is_submit && $js_protect ){
			$values_correct = $this->__js_clear($values);
		}
		#exit();
		#Заполняем масcив для шаблона
		$index = sizeof($this->fields);
		for($i=0; $i<$index; $i++){
			if ( $this->cf_is_submit ){
				$value = $values_correct[$this->fields[$i]->name];
			}else{
				$value = $this->fields[$i]->value;
			}
			$this->fields[$i]->set_value( $value );
			if ( is_array($vars) ){
				if ( !$this->fields[$i]->no_show ){
					$vars['__value_'.$this->fields[$i]->name] = $value;
				}
			}
			#добавляем ункальные параметры поля
			$this->fields[$i]->set_unique_vars( $vars );
		}
	}

#-------------------------------------------------------------------------------------------------------------------------

	function cf_gen_template( $show = 0, $tarea = 'TAREA_ID' ){
		$res = '';
		$index = sizeof($this->fields);
		for($i=0; $i<$index; $i++){
			$field_vars = $this->fields[$i]->gen_template_vars( $tarea );
			$fields_loop[]['FIELD_BODY'] = $this->__parse_template( dirname(__FILE__).'/tmpl/fields/'.strtolower($this->fields[$i]->type).'.vtmpl', $field_vars );
		}
		$form_vars = array();
		$form_vars['NAME'] = $this->name;
		$form_vars['FIELD_LOOP'] = & $fields_loop;
		$form_vars['TAREA_NAME'] = $tarea;
		$res = $this->__parse_template( dirname(__FILE__).'/tmpl/form.vtmpl', $form_vars );
		unset( $form_vars );
		$res = str_replace('-TMPL_', 'TMPL_', $res);
		if ( $show ){
			print str_replace("\n", "<br>", htmlspecialchars( $res ) );
		}
		return $res;
	}

#-------------------------------------------------------------------------------------------------------------------------

	function cf_check_form(){
		$res = true;
		$index = sizeof($this->fields);
		for($i=0; $i<$index; $i++){
			if ( $this->fields[$i]->ch_find_error ){
				$res = false;
				break;
			}
		}
		return $res;
	}

#-------------------------------------------------------------------------------------------------------------------------

	function cf_error_fill_template( & $vars ){
		$index = sizeof($this->fields);
		for($i=0; $i<$index; $i++){
			if ( $this->fields[$i]->ch_find_error && $this->__err_info[$this->fields[$i]->ch_find_error]['NAME'] ){
				$vars['__err_'.$this->fields[$i]->name.$this->__err_info[$this->fields[$i]->ch_find_error]['NAME']] = 1;
			}
		}
	}

#-------------------------------------------------------------------------------------------------------------------------

	function cf_kill_save_values( $fname = '' ){
		$res = array();
		if ( !$fname )
		    $fname = $this->name;
		if ( !headers_sent() ){
			session_start();
			if ( session_is_registered($fname) ){
            	unset( $_SESSION[$fname] );
            }
		}else{			$this->__raise_error(__FC_ERR_CANT_CREATE_SESSION, __FILE__, __LINE__);
		}
		return $res;
	}

#-------------------------------------------------------------------------------------------------------------------------

	function cf_get_save_values( $fname ){
		$res = array();
		if ( !headers_sent() ){
			session_start();
			if ( session_is_registered($fname) ){
            	$res = $_SESSION[$fname];
            }
		}else{			$this->__raise_error(__FC_ERR_CANT_CREATE_SESSION, __FILE__, __LINE__);
		}
		return $res;
	}

#-------------------------------------------------------------------------------------------------------------------------

	function cf_save_values(){
		if ( !headers_sent() ){
			session_start();
			$this->cf_kill_save_values();
			$_SESSION[$this->name] = array();
			$index = sizeof($this->fields);
			for($i=0; $i<$index; $i++){
				if ( !$this->fields[$i]->no_save ){
					$_SESSION[$this->name][$this->fields[$i]->name] = $this->fields[$i]->value;
				}
			}
		}else{			$this->__raise_error(__FC_ERR_CANT_CREATE_SESSION, __FILE__, __LINE__);
		}
	}

#-------------------------------------------------------------------------------------------------------------------------

	function cf_restore_values( & $vars, $js_protect = 1 ){
		$values = $this->cf_get_save_values($this->name);
		if ( !empty($values) ){
			$values['__submit'] = 1;
			$this->cf_set_values($values, $vars, $js_protect);
			#uncheck submit
			$this->cf_is_submit = false;
		}else{
			$values['__submit'] = 0;
			$this->cf_set_values($values, $vars, $js_protect);
		}
	}

#-------------------------------------------------------------------------------------------------------------------------

	function cf_get_values(){
		$res = array();
		$index = sizeof($this->fields);
		for($i=0; $i<$index; $i++){
			$res[$this->fields[$i]->name] = $this->fields[$i]->value;
		}
		return $res;
	}

#-------------------------------------------------------------------------------------------------------------------------

	function cf_store_uploaded_files(){
		$index = sizeof( $this->fields );
		for($i=0; $i<$index; $i++){
			$methods = get_class_methods( get_class($this->fields[$i]) );
			if ( in_array('store_uploaded_file', $methods ) ){
				$this->fields[$i]->store_uploaded_file();
			}
		}
	}

#-------------------------------------------------------------------------------------------------------------------------

	function __parse_template( $fname, $vars = array() ){
		$res = '';
		if( file_exists($fname) ){
			$tmpl = & new vlibTemplate($fname);
			if ( is_array($vars) ){
				$keys = array_keys($vars);
				$index = sizeof($keys);
				for($i=0; $i<$index; $i++){
					$name = trim($keys[$i]);
					if ( $name != '' ){
						if ( is_array( $vars[$keys[$i]] ) ){
							$tmpl->setLoop( $name, $vars[$keys[$i]] );
						}elseif ( $name != '' ){
							$tmpl->setVar( $name, $vars[$keys[$i]] );
						}
					}
					unset($name);
				}
			}
			$res = $tmpl->grab();
			unset($tmpl);
		}else{			$this->__raise_error(__FC_ERR_CANT_FOUND_FORM_TEMPLATE, __FILE__, __LINE__, $fname);
		}
		return $res;
	}

#-------------------------------------------------------------------------------------------------------------------------

	function __js_clear( $values ){
		$res = array();
		$error_keys = array_keys( $this->__err_info );
		$ek_index = sizeof($error_keys);
		if ( is_array($values) ){
			$keys = array_keys($values);
			$index = sizeof($keys);
			for($i=0; $i<$index; $i++){
				if ( $keys[$i][0] == '_' ){
					$key = $keys[$i];
					for($j=0; $j<$ek_index; $j++){
						$key = str_replace( $this->__err_info[$error_keys[$j]]['NAME'], '', $key);
					}
					$res[$key] = $values[$keys[$i]];
					unset($key);
				}else{
					$res[$keys[$i]] = $values[$keys[$i]];
				}
			}
		}
		return $res;
	}

#-------------------------------------------------------------------------------------------------------------------------
}

?>